//
//  TSLabelCollectionView.swift
//  Picture
//
//  Created by 王磊 on 28/04/2017.
//  Copyright © 2017 ThreeStone. All rights reserved.
//

import UIKit

extension TSLabelCollectionView {
    
    override static func getInstance() -> TSLabelCollectionView {
        
        let flowLayout = TSLabelFlowLayout()
        
        flowLayout.minimumInteritemSpacing = Label_Section_Item_Min_Space
        
        flowLayout.minimumLineSpacing = Label_Section_Item_Min_Space
        
        flowLayout.sectionInset = UIEdgeInsetsMake(0, Label_Section_Inset_Left, 0, Label_Section_Inset_Right)
        
        return TSLabelCollectionView.getInstance(flowLayout)
    }
    static func getInstance(flowLayout: UICollectionViewFlowLayout) -> TSLabelCollectionView {
        
        return TSLabelCollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
    }
}

class TSLabelCollectionView: UICollectionView {
    
    private var dataArray: Array<AnyObject> = []
    
    internal var defaultSelectedIndexPath: NSIndexPath = NSIndexPath(forItem: 0, inSection: 0)
    
    private var selectedLabel: NSMutableArray = NSMutableArray()
    
    internal weak var labelDelegate: TSLabelCollectionViewDelegate?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        
        commitInitOwnProperties()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}



protocol TSLabelCollectionViewA {
    
    var unsureObervers: Array<CMDBThisObserverBean>? { set get }
}



extension TSLabelCollectionView {
    
    internal func updateData(arr: Array<AnyObject>) {
        
        if !dataArray.isEmpty {
            
            dataArray.removeAll()
        }
        
        dataArray += arr
        
        let first = dataArray.first as! TSLabelBean
        
        first.isSelected = true
        
        dataArray.replaceRange(0..<1, with: [first as AnyObject])
        
        reloadData()
    }
}

private let cellIdentifier: String = "TSLabelCollectionViewCell"

private let reuseHeader: String = "TSLabelCollectionHeaderView"

extension TSLabelCollectionView {
    
    internal func commitInitOwnProperties() {
        
        showsVerticalScrollIndicator = false
        
        showsHorizontalScrollIndicator = false
        
        bounces = true
        
        dataSource = self
        
        delegate = self
        
        registerClass(TSLabelCollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
        
        registerClass(TSLabelCollectionHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: reuseHeader)
        
        clipsToBounds = false
        
        backgroundColor = UIColor.whiteColor()
        
        
    }
}
extension TSLabelCollectionView {
    
}

// MARK: data source
extension TSLabelCollectionView: UICollectionViewDataSource {}

extension TSLabelCollectionView {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return 1
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! TSLabelCollectionViewCell
        
        cell.indexPath = indexPath
        
        cell.updateData(dataArray[indexPath.row])
        
        return cell
    }
}

extension TSLabelCollectionView {
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        
        if kind == UICollectionElementKindSectionHeader {
            
            let header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: reuseHeader, forIndexPath: indexPath) as! TSLabelCollectionHeaderView
            
            return header
        } else {
            
            return UICollectionReusableView()
        }
    }
}
extension TSLabelCollectionView {
    
    func selectItemAtIndexPath(indexPath: NSIndexPath) {
        
        let cell = cellForItemAtIndexPath(indexPath) as! TSLabelCollectionViewCell
        
        if indexPath.row == 0 {
            
            cell.selected(true)
            
            _ = selectedLabel.map({
                
                let label = $0 as! TSLabelBean
                
                let cell = cellForItemAtIndexPath(label.indexPath!) as! TSLabelCollectionViewCell
                
                cell.selected(false)
                
                label.indexPath = nil
                
                label.isSelected = false
            })
            
            selectedLabel.removeAllObjects()
            
        } else {
            
            let tempLabel = dataArray[indexPath.row] as! TSLabelBean
            
            if let _ = tempLabel.indexPath {
                
                tempLabel.isSelected = false
                
                tempLabel.indexPath = nil
                
                selectedLabel.removeObject(tempLabel)
                
                cell.selected(false)
                
                if selectedLabel.count == 0 {
                    
                    let total = cellForItemAtIndexPath(defaultSelectedIndexPath) as! TSLabelCollectionViewCell
                    
                    total.selected(true)
                }
                
            } else {
                
                tempLabel.isSelected = true
                
                tempLabel.indexPath = indexPath
                
                selectedLabel.addObject(tempLabel)
                
                cell.selected(true)
                
                let total = cellForItemAtIndexPath(defaultSelectedIndexPath) as! TSLabelCollectionViewCell
                
                total.selected(false)
            }
        }
    }
}


// MARK: delegate
extension TSLabelCollectionView: UICollectionViewDelegate {}

extension TSLabelCollectionView {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if unsureObervers != nil {
            
            let argu = TSArguInfo()
            
            argu.data = dataArray[indexPath.item]
            
            argu.view = self
            
            argu.indexPath = indexPath
            
            argu.itemType = TSItemClickType.LabelItem
            
            performSelWithArgu(argu)
            
        } else {
            
            guard let mDelegate = labelDelegate else {
                
                return
            }
            
            guard mDelegate.respondsToSelector(#selector(mDelegate.onLabelCollectionItemSelected)) else {
                
                return
            }
            
            mDelegate.onLabelCollectionItemSelected(dataArray[indexPath.item], indexPath: indexPath)
        }
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        
        return CGSizeMake(100 , Label_Section_Item_Height)
    }
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        return CGSizeMake(CGRectGetWidth(bounds), Label_Section_Header_Height)
    }
}
